package com.dkm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dkm.entity.Module;
import com.dkm.repository.ModuleRepository;
import com.dkm.service.ModuleService;
import com.dkm.util.ResultUtil;
@Service
public class ModuleServiceImpl implements ModuleService {

	//注入模块持久层
	@Autowired
	private ModuleRepository moduleRepository;
	
	@Override
	public List<Module> findAllModules() {
		
		return moduleRepository.findAll();
	}

	@Override
	public Module getModuleByModule_id(Integer module_id) {
		//Module module=.getOne(module_id);
		//System.out.println("service module>"+module);
		return moduleRepository.findById(module_id).get();
	}

	@Transactional //开启事务
	@Override
	public ResultUtil saveAndFlushModule(Module module) {
		ResultUtil resultUtil=null;
		String operation="";
		
		if(module.getModule_id()!=null) {
			operation="修改";
		}else {
			operation="添加";
		}
		
		Module m=moduleRepository.saveAndFlush(module);
		if(m!=null) {
			resultUtil=new ResultUtil(0, operation+"成功！", m);
		}else {
			resultUtil=new ResultUtil(-1, operation+"失败！", null);
		}
		return resultUtil;
	}

	@Transactional //开启事务
	@Override
	public ResultUtil deleteModule(Integer module_id) {
		Module module=new Module();
		module.setModule_id(module_id);
		//查询该模块是否有子模块
		List<Module> children=moduleRepository.getChildrenByModule_id(module_id);
		if(children.size()>0) {
			return new ResultUtil(-1, "无法删除！该模块下有【"+children.size()+"】个子模块！", null);
		}
		try {
			moduleRepository.delete(module);
			return new ResultUtil(0, "删除成功！", null);
		} catch (Exception e) {
			return new ResultUtil(-1, "删除失败！", null);
		}
	}

}
